package com.example.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.common.utils.Constant;
import com.example.common.utils.R;
import com.example.common.vo.MemberRespVo;
import com.example.gulimall.order.constant.OrderConstant;
import com.example.gulimall.order.entity.OrderItemEntity;
import com.example.gulimall.order.enume.OrderStatusEnum;
import com.example.gulimall.order.feign.CartFeignService;
import com.example.gulimall.order.feign.MemberFeignService;
import com.example.gulimall.order.feign.ProductFeignService;
import com.example.gulimall.order.feign.WmsFeignService;
import com.example.gulimall.order.interceptor.LoginUserInterceptor;
import com.example.gulimall.order.service.OrderItemService;
import com.example.gulimall.order.to.OrderCreateTo;
import com.example.gulimall.order.vo.*;
import exception.NoStockException;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.Buffer;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.order.dao.OrderDao;
import com.example.gulimall.order.entity.OrderEntity;
import com.example.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import to.mq.OrderTO;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private  ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal<>();
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 本地事务，再分布式系统中，只能控制自己的回滚，控制不了其他服务的回滚
     * 分布式事务：产生最大原因，网络问题+分布式机器
     * @param orderSubmitVo
     * @return
     */
   // @GlobalTransactional 并发能力太差，不适合高并发业务
    @Transactional
    @Override
    public SubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {

        confirmVoThreadLocal.set(orderSubmitVo);
        SubmitResponseVo responseVo = new SubmitResponseVo();
        responseVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //创建订单，
        // TODO 1验令牌，
        String orderToken = orderSubmitVo.getOrderToken();
        // 这里为防止用户点击速度快，第一次请求redis还没查询出结果，但是第二次查询已经出结果了没删刚好两次一起通过
        //因此这里删除和验证令牌需要一个原子操作，使用脚本 对比和删除token
        //脚本返回的都是0和1 0代表令牌失败，1 成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
       // String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
        //原子验证和删除
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);

        if (result==0L){
            //验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //验证成功
            //创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
           if (Math.abs(payAmount.subtract(payPrice).doubleValue()) <0.01){
               //金额对比
               //TODO 3 保存订单
               saveOrder(order);
               //TODO 4 锁库存,只要有异常，抛出，回滚订单数据
               // 订单号，所有订单项信息（skuid,skuname, num）

               WareSkuLockVo lockVo  = new WareSkuLockVo();
               lockVo.setOrderSn(order.getOrder().getOrderSn());
               List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                   OrderItemVo itemVo = new OrderItemVo();
                   itemVo.setSkuId(item.getSkuId());
                   itemVo.setCount(item.getSkuQuantity());
                   itemVo.setTitle(item.getSkuName());
                   return  itemVo;
               }).collect(Collectors.toList());
               lockVo.setLocks(locks);
               // TODO 远程锁库存
               //1 为了保证高并发，库存服务自己回滚，可以发消息给库存服务
               //2 库存服务本身也可以使用自动解锁，消息队列
               R r = wmsFeignService.orderLockStock(lockVo);
               if (r.getCode().equals(0)){
                   //锁成功了
                   responseVo.setOrder(order.getOrder());
                   // TODO 5 远程扣减积分，出异常
                  // int i=10/0; 模拟异常，让库存回滚
                   // TODO 订单创建成功，发送消息给MQ
                   rabbitTemplate.convertAndSend("order-event-exchange",
                           "order.create.order",
                           order.getOrder()
                           );
                   return  responseVo;

               }else {
                   String msg =(String) r.get("msg");
                   throw new NoStockException(msg);
                  // responseVo.setCode(3);
                  // return  responseVo;
               }


           }else {
               responseVo.setCode(2); //金额对比失败
               return  responseVo; 
           }


        }
        // TODO 2验价格，
        // TODO 3锁库存。。。。最
        // TODO 4终下单成功来到支付选择页， 下单失败回到订单确认页重新确认订单信息
    }

    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        //保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder(){
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1 生成一个订单号，用mabites提供的这个方法可以生成一个唯一id
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        // 2 获取到所有的订单项
         List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //3 验价
        //计算价格,积分相关信息
        computePrice(orderEntity,itemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(itemEntities);
        return  orderCreateTo;
    }

    /**
     * 验价的方法
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal couponAmount=new BigDecimal("0");
        BigDecimal integrationAmount=new BigDecimal("0");
        BigDecimal promotionAmount=new BigDecimal("0");
        BigDecimal giftIntegration=new BigDecimal("0");
        BigDecimal giftGrowth=new BigDecimal("0");
        //订单总额 叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
             couponAmount =couponAmount.add(entity.getCouponAmount());
             integrationAmount =integrationAmount.add( entity.getIntegrationAmount());
             promotionAmount =promotionAmount.add( entity.getPromotionAmount());
            total=total.add(entity.getRealAmount());
            giftIntegration.add(new BigDecimal(  entity.getGiftIntegration().toString()));
           giftGrowth.add(new BigDecimal(  entity.getGiftGrowth().toString()));
        }
        //订单价格相关
        //total已经将各种优惠后的价格计算好了，因此只需再 加运费
        orderEntity.setTotalAmount(total);
        //设置应付金额 总额加运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //订单总共优惠的总额
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegration(integrationAmount.intValue());
        orderEntity.setCouponAmount(couponAmount);

        //设置积分等信息
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 构建一个订单 基本信息
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity =  new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //获取收获地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>(){});
        //设置运费
        orderEntity.setFreightAmount(fareResp.getFare());
        //设置收获人信息
        orderEntity.setReceiverCity(fareResp.getAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddressVo().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddressVo().getName());
        orderEntity.setReceiverPhone(fareResp.getAddressVo().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddressVo().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddressVo().getProvince());
        orderEntity.setReceiverRegion(fareResp.getAddressVo().getRegion());

        //设置订单的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);// 自动确认时间 七天
        return orderEntity;
    }

    /**
     * 构建订单的所有订单项数据 商品信息
     * @return
     */
    private List<OrderItemEntity>  buildOrderItems(String orderSn){
        //最后确认每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems!=null&&currentUserCartItems.size()>0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
               // itemEntity.setIntegrationAmount();
                return itemEntity;

            }).collect(Collectors.toList());
            return itemEntities;
        }
        return  null;

    }

    /**
     * 构建指定的某一个订单项的数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem){
        OrderItemEntity itemEntity = new OrderItemEntity();

        // 商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfVo data = r.getData(new TypeReference<SpuInfVo>() {
        });
        if (data!=null){
            itemEntity.setSpuId(data.getId());
            itemEntity.setSpuBrand(data.getBrandId().toString());
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setCategoryId(data.getCatalogId());
        }
        //商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 商品的优惠信息，不做
        // 积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //订单项的价格信息
        //促销价，这里写死，如果需要可以自己去查
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        //优惠价 这里写死，如果需要可以自己去查
        itemEntity.setCouponAmount(new BigDecimal("0"));
        // 积分抵扣 这里写死，如果需要可以自己去查
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
       //原来的价格
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        //当前订单项的实际金额  总额减去各种优惠
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }





    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *  查询订单查询页需要的数据
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取之前的请求数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddresFuture = CompletableFuture.runAsync(() -> {
            //RequestContextHolder 由于这个工具用的是ThreadLocal共享同一线程数据，异步他会开一个新的线程导致
            //拦截器中RequestContextHolder为空，所以下面这行代码让他共享主线程的threadLocal
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1远程查询会员收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        },executor);
        CompletableFuture<Void> getCartFuture = CompletableFuture.runAsync(() -> {
            //2远程查询购物车所有选中的购物项
            // 同步代码： feign在远程调用之前要构造请求，调用很多的拦截器 RequestInterceptor interceptor:requestIntercptor
            //异步还要加这个
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(currentUserCartItems);
        },executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIds);
            List<SkuStockVo> data = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data!=null){
                Map<Long,Boolean> map= data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId,SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        });


        // 3 查询用户积分
        Integer integration = memberRespVo.getIntegration();


        confirmVo.setIntegration(integration);
        // 其他数据vo里自动计算
        try {
            //TODO 放重令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            confirmVo.setOrderToken(token); //给页面的放重令牌
            redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
            CompletableFuture.allOf(getAddresFuture,getCartFuture).get();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //TODO 5 防重令牌。幂等性章节说
        return  confirmVo;

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
        return  orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //关闭订单之前，当前这个订单的最新状态
        OrderEntity orderEntity1 = this.getById(orderEntity.getId());
        //关单
        if (orderEntity1.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            // 关单逻辑是在30分组以后，可能其他属性已经发生变化，为了防止我们应该只改变状态
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(orderEntity1,orderTO);
            rabbitTemplate.convertAndSend("order-event-exchange",
                    "order.release.other",
                    orderTO);
        }
    }

}